package com.homer.commons.sscpprotocol.server.impl;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;

import com.homer.commons.sscpprotocol.server.base.AbstractMessage;
import com.homer.commons.sscpprotocol.server.base.AbstractMessageDecoder;

public class ResponseDecoder extends AbstractMessageDecoder {
	private static final String MESSAGE_ATTR_NAME = ResponseDecoder.class
			.getName() + ".message";

	private static final Object MESSAGE_BODY_LEN_ATTR_NAME = MESSAGE_ATTR_NAME
			+ ".bodylen";

	public ResponseDecoder(int version) {
		super(version);
	}

	public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
		MessageDecoderResult result = super.decodable(session, in);
		if ((result == MessageDecoderResult.OK) && (in.remaining() < version)) {
			return MessageDecoderResult.NEED_DATA;
		}

		return result;
	}

	protected AbstractMessage decodeMessage(IoSession session, IoBuffer in) {
		if (in.remaining() < version) {
			return null;
		}
		SscpResponseImpl m = (SscpResponseImpl) session
				.getAttribute(MESSAGE_ATTR_NAME);
		if (m == null) {
			m = new SscpResponseImpl();
		}
			

			m.setSync_head(in.get());
			byte[] mainD = new byte[4];
			in.get(mainD);
			m.setMainDeviceID(mainD);
			byte[] slaveD = new byte[2];
			in.get(slaveD);
			m.setSlaveDevideID(slaveD);
			m.setKey(in.get());
			m.setCommandLength(in.get());

			session.setAttribute(MESSAGE_BODY_LEN_ATTR_NAME,
					m.getCommandLength());
			int bodyLength = m.getCommandLength();
			if (bodyLength > 0) {
				byte[] content = new byte[bodyLength];
				in.get(content);
				m.setContent(content);

			}

			m.setSync_end(in.get());

			session.setAttribute(MESSAGE_ATTR_NAME, m);
		
		session.removeAttribute(MESSAGE_BODY_LEN_ATTR_NAME);
		session.removeAttribute(MESSAGE_ATTR_NAME);
		return m;
	}

	public void finishDecode(IoSession session, ProtocolDecoderOutput out)
			throws Exception {
	}
}